﻿#include "SVDetectController.h"

SVDetectController::SVDetectController(QWidget *widget, QObject *parent)
    : QObject(parent)
    , mDetectView(new SVDetectView(widget))
    , mCamera(nullptr)
    , mCalculateModel(nullptr)

{
    connect(
        mDetectView, &SVDetectView::startDetection, this, &SVDetectController::onStartDetection);
    connect(mDetectView, &SVDetectView::stopDetection, this, &SVDetectController::onStopDetection);
}

QWidget *SVDetectController::getView() const
{
    return mDetectView;
}

void SVDetectController::loadCamera(SVCamera *camera)
{
    mCamera = camera;
    connect(mCamera, &SVCamera::frameReady, this, &SVDetectController::onCaptureImage);
}

void SVDetectController::loadCalculateModel(SVCalculateModel *model)
{
    mCalculateModel = model;
}

void SVDetectController::onStartDetection()
{
    mCamera->open();
}

void SVDetectController::onStopDetection()
{
    mCamera->close();
}

void SVDetectController::onCaptureImage(const QImage &image)
{
    mCalculateModel->matchPCBTemplate(image, TEMPLATEMODEL->getTemplateFeatures());
    QList<QRect> result = mCalculateModel->detectDifferenceRegions(image);
    QPixmap pixmap = QPixmap::fromImage(image);
    QPainter painter(&pixmap);
    painter.setPen(QPen(Qt::red, 3));
    for (const QRect &rect : result) {
        painter.drawRect(rect);
    }
    mDetectView->setDetectResult(pixmap);
}
